﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace <%=@ui_namespace%>
{
    public class <%= @table.TableName %>SelectEventArgs : EventArgs
    {
        public decimal ID;
        public <%= @table.TableName %>SelectEventArgs(decimal id)
        {
            ID = id;
        }
    }

    public delegate void <%= @table.TableName %>SelectHandler(object sender, <%= @table.TableName %>SelectEventArgs e);

    public partial class ucList_<%= @table.TableName %> : System.Web.UI.UserControl
    {
        public event <%= @table.TableName %>SelectHandler ItemSelected;
        public event EventHandler NewRecordRequested; 
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadList();
        }

        public void LoadList()
        {
            <%=@model_namespace%>.<%= @table.TableName %> items = new <%=@model_namespace%>.<%= @table.TableName %>();
            SqlDataSource1.SelectCommand = items.Query.GenerateSQL();
            SqlDataSource1.ConnectionString = items.RawConnectionString;
            gvList.DataBind();
        }

        protected void handleNewRecord(object sender, EventArgs e)
        {
            if (NewRecordRequested != null)
            {
                
                NewRecordRequested(this, e);
            }
        }

        protected void handleRowSelect(Object src, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                // get the row index stored in the CommandArgument property
                int index = Convert.ToInt32(e.CommandArgument);

                // get the GridViewRow where the command is raised
                DataKey dk = gvList.DataKeys[index];
               

                // for bound fields, values are stored in the Text property of Cells [ fieldIndex ]
                string strID = dk.Value.ToString();

                if (ItemSelected != null)
                {
                    decimal id = decimal.Parse(strID);
                    <%= @table.TableName %>SelectEventArgs args = new <%= @table.TableName %>SelectEventArgs(id);
                    ItemSelected(this, args);
                }
                
            }
        }
    }
}